package com.linzi.common.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 此转换器可以自动转换为的java对象
 * 注解中设置的是对应的jdbctype，mysql的json对象对应的jdbctype为VARCHAR。
 *
 * @author chenmaolin
 * @date: 2021/12/6 16:15
 */

@MappedTypes(value = {JSONArray.class})
@MappedJdbcTypes(value = {JdbcType.VARCHAR})
public class JsonArrayTypeHandler extends BaseTypeHandler<JSONArray> {

    public JsonArrayTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONArray parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String data = resultSet.getString(columnName);
        return StringUtils.isBlank(data) ? new JSONArray() : JSON.parseArray(data);
    }

    @Override
    public JSONArray getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String data = resultSet.getString(columnIndex);
        return StringUtils.isBlank(data) ? new JSONArray() : JSON.parseArray(data);
    }

    @Override
    public JSONArray getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String data = callableStatement.getString(columnIndex);
        return StringUtils.isBlank(data) ? new JSONArray() : JSON.parseArray(data);
    }
}